<template>
  <el-card>
    <!-- 面包屑 -->
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">商品列表</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">商品添加</a></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
    <!-- 步骤条 -->
    <el-steps :active="active * 1" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- 标签页 -->
    <el-form
      :model="formInfo"
      :rules="formRules"
      ref="form"
      label-width="180px"
    >
      <el-tabs
        tab-position="left"
        v-model="active"
        :before-leave="beforeleave"
        @tab-click="tabclick"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="formInfo.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="价格" prop="goods_price">
            <el-input v-model="formInfo.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="goods_number">
            <el-input v-model="formInfo.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="重量" prop="goods_weight">
            <el-input v-model="formInfo.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="formInfo.goods_cat"
              :options="cate_list"
              clearable
              :props="{
                checkStrictly: true,
                value: 'cat_id',
                label: 'cat_name'
              }"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-row v-for="item in many_list" :key="item.id">
            <el-col :span="20">
              <el-form-item :label="item.attr_name">
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    :label="val"
                    v-for="(val, index) in item.attr_vals"
                    :key="index"
                  ></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-row v-for="item in only_list" :key="item.id">
            <el-col :span="10">
              <el-form-item :label="item.attr_name">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            action="http://122.51.249.55:5000/api/private/v1/upload"
            :headers="headers"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="content" ref="myQuillEditor"> </quill-editor>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="goodsSubmit"
            >添加</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>
</template>

<script>
// 导入富文本编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
// 导入lodash
import lodash from "lodash";
export default {
  // 富文本编辑器组件
  components: {
    quillEditor
  },
  data() {
    return {
      active: "0",
      formInfo: {
        goods_name: "1",
        goods_cat: [1, 3, 6],
        goods_price: "1",
        goods_number: "1",
        goods_weight: "1",
        goods_introduce: "1",
        pics: [],
        attrs: ""
      },
      cate_list: [], //商品分类,
      many_list: [],
      only_list: [],
      // checkList: [],
      fileList: [], //图片列表
      dialogVisible: false,
      dialogImageUrl: "",
      content: "",
      headers: {
        Authorization: JSON.parse(sessionStorage.getItem("shop_userinfo")).token
      },
      formRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ],
        pics: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
        attrs: [{ required: true, message: "请选择商品分类", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getAllCateList();
  },
  computed: {
    //   三级分类ID
    cateId() {
      if (this.formInfo.goods_cat.length === 3) {
        return this.formInfo.goods_cat[2];
      } else {
        return null;
      }
    }
  },
  methods: {
    //   获取分类列表
    async getAllCateList() {
      let { data: res } = await this.$axios.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cate_list = res.data;
    },
    beforeleave(activeName, oldActiveName) {
      if (!this.cateId && oldActiveName == 0) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    // 点击切换事件
    async tabclick() {
      let sel = "";
      if (this.active === "1") {
        sel = "many";
      } else if (this.active === "2") {
        sel = "only";
      } else {
        return;
      }
      let { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel }
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      if (sel === "many") {
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals === 0 ? [] : item.attr_vals.split(",");
        });
      }
      this[sel + "_list"] = res.data;
    },
    // 图片预览
    handlePreview(file) {
      console.log(file);
      this.dialogVisible = true;
      this.dialogImageUrl = file.response.data.url;
    },
    // 图片移除
    handleRemove(file) {
      let tmppath = file.response.data.tmp_path;
      let index = this.formInfo.pics.findIndex(item => item.pic === tmppath);
      this.formInfo.pics.splice(index, 1);
    },
    // 图片上传成功
    handleSuccess(response) {
      console.log(response);
      this.formInfo.pics.push({ pic: response.data.tmp_path });
    },
    goodsSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return;
        // 表单数据生拷贝
        let deepForm = lodash.cloneDeep(this.formInfo);
        // 处理商品分类
        deepForm.goods_cat = deepForm.goods_cat.join(",");
        // 处理商品参数
        let temp_arr = [];
        this.many_list.forEach(item => {
          if (item.attr_vals.length) {
            temp_arr.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(",")
            });
          }
        });
        // 商品属性
        this.only_list.forEach(item => {
          if (item.attr_vals.length) {
            temp_arr.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            });
          }
        });
        deepForm.attrs = temp_arr;
        // 发送请求
        let { data: res } = await this.$axios.post("goods", deepForm);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("创建成功");
        this.$router.push("/goods");
      });
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.ql-editor {
  min-height: 300px;
}
</style>